package com.demo.apparel.controller.uniapp;

import com.demo.apparel.common.Result;
import com.demo.apparel.utils.COSUploadUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/wx/upload")
@Tag(name = "示例图片存储接口", description = "腾讯云")
public class UploadController {

    private final COSUploadUtils cosUploadUtils;

    public UploadController(COSUploadUtils cosUploadUtils) {
        this.cosUploadUtils = cosUploadUtils;
    }

    /**
     * 上传单个文件（前端 form-data 提交）
     * POST /upload/file
     */
    @PostMapping("/file")
    public String uploadFile(@RequestParam("file") MultipartFile file,
                             @RequestParam(defaultValue = "images") String folder) {
        return cosUploadUtils.upload(file, folder);
    }

    /**
     * 批量上传多个文件
     */
//    @PostMapping("/files")
//    public List<String> uploadFiles(@RequestParam("files") MultipartFile[] files,
//                                    @RequestParam(defaultValue = "images") String folder) {
//        List<String> urls = new ArrayList<>();
//        for (MultipartFile file : files) {
//            urls.add(cosUploadUtils.upload(file, folder));
//        }
//        return urls;
//    }
    @PostMapping("/files")
    public Result<List<String>> uploadFiles(@RequestParam("files") MultipartFile[] files,
                                            HttpServletRequest request) {
        try {
            String userId = (String) request.getAttribute("userId");
            String folder = "images/" + userId;

            List<String> urls = new ArrayList<>();
            for (MultipartFile file : files) {
                urls.add(cosUploadUtils.upload(file, folder));
            }

            return Result.success(urls);
        } catch (Exception e) {
            return (Result<List<String>>) Result.error("批量上传失败: ","上传失败");
        }
    }


    /**
     * 删除文件
     * @param fileKey COS 对象的 Key，例如 "images/xxx.png"
     */
    @DeleteMapping("/file")
    public String deleteFile(@RequestParam String fileKey) {
        cosUploadUtils.delete(fileKey);
        return "删除成功: " + fileKey;
    }

    @DeleteMapping("/files")
    public Result<String> deleteFiles(@RequestBody List<String> fileKeys) {
        try {
            for (String key : fileKeys) {
                cosUploadUtils.delete(key);
            }
            return Result.success("删除成功");
        } catch (Exception e) {
            return (Result<String>) Result.error("批量删除失败: ","删除成功");
        }
    }

}
